package jwt

import (
	"github.com/golang-jwt/jwt/v5"
	"log"
	"time"
)

// @secretKey: JWT 加解密密钥
// @iat: 时间戳
// @seconds: 过期时间，单位秒
// @payload: 数据载体

func GetJwtToken(userId string) (string, error) {
	claims := make(jwt.MapClaims)
	iat := time.Now().Unix()
	claims["exp"] = iat + 86400
	claims["iat"] = iat
	claims["userId"] = userId
	token := jwt.New(jwt.SigningMethodHS256)
	secretKey := "000000"
	token.Claims = claims
	return token.SignedString([]byte(secretKey))
}

func GetToken(tokenString string) (string, error) {
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (any, error) {
		secretKey := "000000"
		return []byte(secretKey), nil

	}, jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}))
	if err != nil {

		log.Println("失败", err)
		return "", err
	}

	if claims, ok := token.Claims.(jwt.MapClaims); ok {
		return claims["userId"].(string), nil
	} else {
		return "", nil
	}
}
